package com.jdk.demo.unsafe;

import java.lang.reflect.Field;
import java.util.HashMap;
import sun.misc.Unsafe;

public class UnsafeTest3 {
	
	public static void main(String[] args) throws Exception {
		Unsafe unsafe = getUnsafeInstance();
		// 调用Unsafe来实例化，Unsafe.allocateInstance()只会给对象分配内存，并不会调用构造方法，所以这里只会返回int类型的默认值0
		User user = (User) unsafe.allocateInstance(User.class);
		System.out.println(user.getAge());
		
        Field age = user.getClass().getDeclaredField("age");
        unsafe.putInt(user, unsafe.objectFieldOffset(age), 20);
        // 打印20
        System.out.println(user.getAge());
	}

	private static Unsafe getUnsafeInstance() throws Exception {
		// 通过反射获取rt.jar下的Unsafe类
		Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
		theUnsafeInstance.setAccessible(true);
		// return (Unsafe) theUnsafeInstance.get(null);是等价的
		return (Unsafe) theUnsafeInstance.get(Unsafe.class);
	}

}
